package cn.jingyuan.swan.cloud.feign;

import cn.jingyuan.bee.utils.IdUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 修复 feign 请求头丢失，描述：
 * <pre>
 *     1、解决微服务之间 feign 调用请求头丢失的问题
 *     2、加入微服务之间传递的唯一请求标识，便于追踪
 * </pre>
 * <p>
 * 请求标识：x-request-id
 */
@Slf4j
public class FeignRequestHeaderInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        if (log.isDebugEnabled()) {
            log.debug(this.getClass().getSimpleName() + " apply before");
        }

        HttpServletRequest httpServletRequest = getHttpServletRequest();
        if (null != httpServletRequest) {
            Map<String, String> headers = getHeaders(httpServletRequest);
            // 传递所有请求头，防止部分丢失
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                template.header(entry.getKey(), entry.getValue());
            }

            // 微服务之间传递的唯一标识，区分大小写所以通过 httpServletRequest 获取
            String xid = httpServletRequest.getHeader(FeignConstants.X_REQUEST_ID);
            if (StringUtils.isEmpty(xid)) {
                xid = IdUtils.fastSimple();
                template.header(FeignConstants.X_REQUEST_ID, xid);
            }

            if (log.isDebugEnabled()) {
                log.debug(this.getClass().getSimpleName() + " : " + template.toString());
                log.debug(this.getClass().getSimpleName() + " apply end");
            }
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        if (enumeration != null) {
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
        return map;
    }

}
